package org.ns.framework.datasource.mybatis;

import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.TransactionIsolationLevel;
import org.ns.framework.datasource.database.Transaction;

/**
 * Mybatis 数据事务管理.
 * 
 * @author zhangxingyu
 *
 */
public interface TransactionManage extends AutoCloseable, Transaction {
	/**
	 * 事务提交
	 * 
	 * @return
	 */
	CommitResult commit();

	/**
	 * 发生截断操作, 开启一个新的事务进行传递.
	 */
	MybatisTransactionSegment segment();

	
//	default void segment(Consumer<TransactionManage> consumer) {
//		try (TransactionManage tx = segment()) {
//			consumer.accept(tx);
//		}
//	}
	
	/**
	 * 事务关闭, 并回滚.
	 */
	void close();

	long getId();

	/**
	 *
	 * @param executorType SIMPLE, REUSE, BATCH(批处理)
	 * @return
	 */
	public static TransactionManage create(ExecutorType executorType) {
		return newBuilder()
				.executorType(executorType)
				.build();
	}
	
	public static TransactionManage createReuse() {
		return create(ExecutorType.REUSE);
	}
	
//	public static TransactionManage create(ExecutorType executorType, boolean autoCommit) {
//		return newBuilder()
//				.executorType(executorType)
//				.autoCommit(autoCommit)
//				.build();
//	}

	public static TransactionManage create() {
		return newBuilder() //
				.build();
	}
	
//	public static TransactionManage autoCommit() {
//		return newBuilder() //
//				.autoCommit()
//				.build();
//	}
	public static TransactionManage inherit() {
		return newBuilder() //
				.inherit()
				.build();
	}
	public static TransactionManage create(ExecutorType executorType, TransactionIsolationLevel level) {

		return newBuilder() //
				.executorType(executorType) // 执行方式
				.level(level) // 事务级别
				.build();
	}

	public static MybatisTransactionManageBuilder newBuilder() {
		return MybatisTransactionManageBuilder.newBuilder();
	}

	public static TransactionManage get() {
		return MybatisTransactionChain.get();
	}

	public static MybatisTransactionSegment prepareSegment() {
		TransactionManage tx = get();
		if (tx != null) {
			return tx.segment();
		} else {
			return new MybatisTransactionSegment();
		}
	}
	
}
